package com.daisuxia.back.controller;

import net.sf.json.JSONArray;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.daisuxia.back.dao.ISmsUserDao;
import com.daisuxia.back.dao.ITemplateSmsDao;
import com.daisuxia.back.result.JsonResult;
import com.daisuxia.back.service.*;
import com.daisuxia.back.utils.*;
import com.daisuxia.config.PayContents;
import com.daisuxia.constant.Constant;
import com.daisuxia.web.pojo.*;
import com.daisuxia.web.util.DateUtil;
import com.daisuxia.web.util.JSONUtil;
import com.daisuxia.web.util.PageConfig;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * 我的催收订单控制层
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("collectionOrder/")
public class MyCollectionOrderController extends BaseController {

	private static Logger logger = LoggerFactory
			.getLogger(MyCollectionOrderController.class);

	// 公司
	@Autowired
	private IMmanLoanCollectionCompanyService mmanLoanCollectionCompanyService;
	// 订单
	@Autowired
	private IMmanLoanCollectionOrderService mmanLoanCollectionOrderService;

	// 用户信息
	@Autowired
	private IMmanUserInfoService mmanUserInfoService;
	@Autowired
	private IBackModuleService backModuleService;
	@Autowired
	private IMmanLoanCollectionStatusChangeLogService mmanLoanCollectionStatusChangeLogService;
	@Autowired
	private IMmanLoanCollectionRecordService mmanLoanCollectionRecordService;
	@Autowired
	private IBackUserService backUserService;
	@Autowired
	private ITemplateSmsDao templateSmsDao;
	@Autowired
	private ICreditLoanPayDetailService creditLoanPayDetailService;
	@Autowired
	private IMmanUserLoanService mmanUserLoanService;
	@Autowired
	private IAuditCenterService auditCenterService;
	@Autowired
	private ISysDictService sysDictService;
	@Autowired
	private ICreditLoanPayService creditLoanPayService;
	@Autowired
	private ISysUserBankCardService sysUserBankCardService;
	@Autowired
	private ISmsUserService smsUserService;
	@Autowired
	private IMmanUserRelaService mmanUserRelaService;
	@Autowired
	private ISmsUserDao iSmsUserDao;	
	@Autowired
	private IMman_loan_collection_orderdeductionService collection_orderdeductionService;

	@Autowired
	private TemplateSmsService service;

	@Autowired
	private ICountCollectionAssessmentService countCollectionAssessmentService;

	@Autowired
	private ICountCollectionManageService countCollectionManageService;
	@Autowired
	private IFengKongService fengKongService;
	@Autowired
	private ICreditLoanPayService CreditLoanPayService;
	/**
	 * 我的订单初始化加载查询
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("getListCollectionOrder")
	public String getListCollectionOrder(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		HashMap<String, Object> params = this.getParametersO(request);

		BackUser backUser = (BackUser) request.getSession().getAttribute(
				Constant.BACK_USER);
		List<BackUserCompanyPermissions> CompanyPermissionsList = backUserService
				.findCompanyPermissions(backUser.getId());
		if (CompanyPermissionsList != null && CompanyPermissionsList.size() > 0) {// 指定公司的订单
			params.put("CompanyPermissionsList", CompanyPermissionsList);
		}
		if (backUser.getRoleId() != null
				&& BackConstant.COLLECTION_ROLE_ID.toString().equals(
						backUser.getRoleId())) {// 如果是催收员只能看自己的订单
			params.put("roleUserId", backUser.getUuid());
			// 催收员查属于自己的组
			params.put("collectionGroup", backUser.getGroupLevel());
		} else {
			// 若组没有 ，则默认查询S1 组
			if (null == params.get("collectionGroup")
					|| StringUtils.isBlank(String.valueOf(params
							.get("collectionGroup")))) {
				params.put("collectionGroup", "3");
			}

		}

		// 查询公司列表
		MmanLoanCollectionCompany mmanLoanCollectionCompany = new MmanLoanCollectionCompany();
		List<MmanLoanCollectionCompany> ListMmanLoanCollectionCompany = mmanLoanCollectionCompanyService
				.getList(mmanLoanCollectionCompany);
		// 分页的订单信息
		PageConfig<OrderBaseResult> page = new PageConfig<OrderBaseResult>();
		page = mmanLoanCollectionOrderService.getPage(params);
		model.addAttribute("ListMmanLoanCollectionCompany",
				ListMmanLoanCollectionCompany);
		model.addAttribute("page", page);
		model.addAttribute("params", params);
		model.addAttribute("userGropLeval", backUser.getRoleId());
		model.addAttribute("dictMap", BackConstant.groupNameMap);
		// 跟进等级
		List<SysDict> levellist = sysDictService.getStatus("xjx_stress_level");
		 HashMap<String, String> levelMap =BackConstant.orderState(levellist);
		model.addAttribute("levellist", levellist);// 用于搜索框保留值
		model.addAttribute("levelMap",levelMap);
		return "mycollectionorder/collectionOrder";
	}

	/**
	 * 添加催记录和催收建议页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("toCollectionRecordAndAdvice")
	public String toAddCollectionRecord(HttpServletRequest request,
			HttpServletResponse response, Model model) {
 		HashMap<String, Object> params = this.getParametersO(request);
		String orderId = null;
		try {
			if ("other".equals(params.get("type"))){
				logger.error("CollectionRecordAndAdvice="+params.get("id").toString());
				String ids = params.get("id").toString();
				String[] list = ids.split(",");
				String userRelaId = list[0];
				orderId = list[1];
				logger.error("CollectionRecordAndAdvice-userRelaId="+list[0]);
				logger.error("CollectionRecordAndAdvice-orderId="+list[1]);
                //根据userRelaId查询联系人
				MmanUserRela userRela = mmanUserRelaService.getUserRealByUserId(userRelaId);
				params.put("infoName",userRela.getInfoName());
				params.put("infoVlue",userRela.getInfoValue());
            }else{
                //根据orderId查询订单
				orderId = params.get("id").toString();
				MmanLoanCollectionOrder	order = mmanLoanCollectionOrderService.getOrderById(orderId);
				params.put("infoName",order.getLoanUserName());
				params.put("infoVlue",order.getLoanUserPhone());
            }
			OrderBaseResult	baseOrder = mmanLoanCollectionOrderService.getBaseOrderById(orderId);
			params.put("loanId",baseOrder.getLoanId());
			params.put("loanUserName",baseOrder.getRealName());
			params.put("loanMoney",baseOrder.getLoanMoney());
			params.put("loanPenlty",baseOrder.getLoanPenlty());
		} catch (Exception e) {
			e.printStackTrace();
		}
		params.put("id",orderId);
		List<SysDict> dictlist = sysDictService.getStatus("xjx_stress_level ");
		model.addAttribute("dictlist", dictlist);// 用于搜索框保留值
		List<SysDict> statulist = sysDictService
				.getStatus("xjx_collection_advise");
		List<FengKong> fengKongList = fengKongService.getFengKongList();
		model.addAttribute("statulist", statulist);
		model.addAttribute("fengKongList", fengKongList);
		model.addAttribute("params", params);// 用于搜索框保留值
		return "mycollectionorder/collectionRecordAndAdvice";
	}

	/**
	 * 添加催收记录和催收建议
	 * 
	 * 
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("addRecordAndAdvice")
	public String addcuishou(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		JsonResult result = new JsonResult("-1", "添加催收记录和催收建议失败");
		Map<String, String> params = this.getParameters(request);
		BackUser backUser = this.loginAdminUser(request);
		try {
			result = mmanLoanCollectionRecordService.saveCollection(params,
					backUser);
			if (result.isSuccessed()
					&& StringUtils.isNotBlank(params.get("stressLevel"))) {
				HashMap<String, Object> topMap = new HashMap<String, Object>();
				topMap.put("id", params.get("id") + "");
				topMap.put("topLevel", params.get("stressLevel"));
				mmanLoanCollectionOrderService.saveTopOrder(topMap);
			}
			params.put("backUserId", backUser.getId().toString());
			params.put("userName",backUser.getUserName());
			result=fengKongService.saveCollectionAdvice(params);
		} catch (Exception e) {
			logger.error(" error", e);
		}
		SpringUtils.renderDwzResult(response, "0".equals(result.getCode()),
				result.getMsg(), DwzResult.CALLBACK_CLOSECURRENT,
				"");
		model.addAttribute("params", params);
		return null;
	}

	private ITongBuService tongBuService;

	/**
	 * 同步测试
	 * 
	 * @param request
	 * @param response
	 * @param orderId
	 * @param model
	 * @return
	 */
	@RequestMapping("tongbu")
	public String tongbu(HttpServletRequest request,
			HttpServletResponse response, String orderId, Model model) {
		tongBuService.tongbu("12462", "12121");
		try {
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 催收流转日志
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("getlistlog")
	public String getCollectionStatusChangeLog(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Map<String, String> params = this.getParameters(request);
		List<MmanLoanCollectionStatusChangeLog> list = null;
		try {
			if (StringUtils.isNotBlank(params.get("id") + "")) {
				MmanLoanCollectionOrder mmanLoanCollectionOrderOri = mmanLoanCollectionOrderService
						.getOrderById(params.get("id").toString());
				list = mmanLoanCollectionStatusChangeLogService
						.findListLog(mmanLoanCollectionOrderOri.getOrderId());
				List<SysDict> statulist = sysDictService
						.getStatus("xjx_collection_order_state");
				// 查询所有的催收状态
				HashMap<String, String> StatuMap = BackConstant
						.orderState(statulist);
				model.addAttribute("StatuMap", StatuMap);
				model.addAttribute("group", BackConstant.groupNameMap);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("params", params);
		model.addAttribute("listlog", list);
		return "mycollectionorder/listlog";
	}

	/**
	 * 跳转到订单详情页
	 * 
	 * @param request
	 * @param response
	 * @param orderId
	 * @param model
	 * @return
	 */
	@RequestMapping("toxianqin")
	public String toxianqin(HttpServletRequest request,
			HttpServletResponse response, String orderId, Model model) {
		HashMap<String, Object> params = this.getParametersO(request);
		if (StringUtils.isNotBlank(params.get("id") + "")) {
			MmanLoanCollectionOrder mmanLoanCollectionOrderOri = mmanLoanCollectionOrderService
					.getOrderById(params.get("id").toString());
			MmanUserLoan userLoan = mmanUserLoanService
					.get(mmanLoanCollectionOrderOri.getLoanId());
			model.addAttribute("userLoan", userLoan);
			model.addAttribute("collectionOrder", mmanLoanCollectionOrderOri);
			MmanUserInfo userInfo = mmanUserInfoService
					.getUserInfoById(mmanLoanCollectionOrderOri.getUserId());
			model.addAttribute("userInfo", userInfo);
			List<CreditLoanPayDetail> detailList = creditLoanPayDetailService
					.findPayDetail(mmanLoanCollectionOrderOri.getPayId());
			BigDecimal payMonery = new BigDecimal(0);
			if (detailList != null) {
				for (CreditLoanPayDetail pay : detailList) {
					payMonery = payMonery.add(pay.getRealMoney()).add(
							pay.getRealPenlty());
				}
			}
			SysUserBankCard userCar = sysUserBankCardService
					.findUserId(mmanLoanCollectionOrderOri.getUserId());			
			/*String  Bank =userCar.getBankCard();
			String Banktto=Bank.substring(4,15);
			String Bankta= Bank.replace(Banktto, "***********");			
			String idNumber=userInfo.getIdNumber();
			String Numbers =idNumber.substring(4,14);
			String Number =idNumber.replace(Numbers, "**********");
			model.addAttribute("Numbers",Number);//身份证号码加密处理
			model.addAttribute("userBank", Bankta); //银行卡号处理
*/			model.addAttribute("userCar", userCar);// 已还金额
			model.addAttribute("payMonery", payMonery);// 已还金额
			model.addAttribute("detailList", detailList);
			// 代扣记录
			List<CollectionWithholdingRecord> withholdList = mmanLoanCollectionRecordService
					.findWithholdRecord(mmanLoanCollectionOrderOri.getId());
			model.addAttribute("withholdList", withholdList);
			model.addAttribute("domaiName", PayContents.XJX_DOMAINNAME_URL);
		}
		model.addAttribute("params", params);
		return "mycollectionorder/myorderDetails";
	}
	/**
	 * 催收记录表
	 * 
	 * @param request
	 * @param response
	 * @param //orderId
	 * @param model
	 * @return
	 */
	@RequestMapping("collectionRecordList")
	public String getloanCollectionRecordList(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		List<MmanLoanCollectionRecord> list = null;
		Map<String, String> params = this.getParameters(request);
		try {
			list = mmanLoanCollectionRecordService.findListRecord(params
					.get("id"));
			model.addAttribute("listRecord", list);
			// 跟进等级
			List<SysDict> levellist = sysDictService
					.getStatus("xjx_stress_level ");
			HashMap<String, String> levelMap = BackConstant
					.orderState(levellist);
			model.addAttribute("levelMap", levelMap);// 用于搜索框保留值
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("params", params);
		return "mycollectionorder/listRecord";
	}


	/**
	 * 跳转扣款页面
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */

	@RequestMapping("tokokuan")
	public String tokokuan(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		JsonResult jsonResult= new JsonResult("-1","请求失败");
		Map<String, String> params = this.getParameters(request);
		if (StringUtils.isNotBlank(params.get("id"))) {
			MmanLoanCollectionOrder mmanLoanCollectionOrderOri = mmanLoanCollectionOrderService
					.getOrderById(params.get("id").toString());
			CreditLoanPay creditLoanPay = creditLoanPayService
					.get(mmanLoanCollectionOrderOri.getPayId());
			model.addAttribute(
					"totalPayMonery",
					creditLoanPay.getReceivablePrinciple().add(
							creditLoanPay.getReceivableInterest()));
		}
		model.addAttribute("params", params);
		return "mycollectionorder/tokokuan";
	}

	/**
	 * 发起扣款
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("kokuan")
	public String kokuan(HttpServletRequest request,HttpServletResponse response, Model model) {
		String url = null;
		String erroMsg = null;
		JsonResult result = new JsonResult("-1", "代扣失败");
		Map<String, String> params = this.getParameters(request);
		BackUser backUser = (BackUser) request.getSession().getAttribute(Constant.BACK_USER);
		try {
			params.put("roleId",backUser.getRoleId());
			params.put("operationUserId", backUser.getId().toString());
			result = mmanLoanCollectionRecordService.xjxWithholding(params);
		} catch (Exception e) {
			logger.error("saveCompany error", e);
		}
		SpringUtils.renderDwzResult(response, "0".equals(result.getCode()),
				result.getMsg(), DwzResult.CALLBACK_CLOSECURRENT,
				params.get("parentId").toString());
		model.addAttribute(MESSAGE, erroMsg);
		model.addAttribute("params", params);
		return url;
	}

	/**
	 * 跳转转派页面
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	// 第一步 选择转派公司
	@RequestMapping("toOrderDistibute")
	public String toOrderDistibute(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		HashMap<String, Object> params = getParametersO(request);
		try {
			if (params.get("ids") != null
					&& StringUtils.isNotBlank(params.get("ids").toString())) {
				if (params.get("groupStatus") != null
						&& !"0".equals(params.get("groupStatus"))) {
					model.addAttribute("message", "只能相同组之间转派。请选择同组的数据");
				}
			} else {
				model.addAttribute("message", "请选择要转派的订单");
			}
			// 催收公司
			MmanLoanCollectionCompany mmanLoanCollectionCompany = new MmanLoanCollectionCompany();
			mmanLoanCollectionCompany.setStatus(BackConstant.ON);// 启用的催收公司
			List<MmanLoanCollectionCompany> companyList = mmanLoanCollectionCompanyService
					.getList(mmanLoanCollectionCompany);
			List<SysDict> dict = sysDictService
					.findDictByType("xjx_overdue_level"); // 催收组
			model.addAttribute("companyList", companyList);// 启用的公司列表
			model.addAttribute("group", dict);
			model.addAttribute("params", params);
		} catch (Exception e) {
			logger.error("getCollectionPage error", e);
		}
		model.addAttribute("params", params);
		return "mycollectionorder/orderDispatch";
	}

	/**
	 * 转派-根据公司查询分组or催收员
	 * 
	 * @param //mmanLoanCollectionOrder
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("findPerson")
	@ResponseBody
	public void orderDisBackUser(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			BackUser backUser = new BackUser();
			backUser.setCompanyId(String.valueOf(params.get("companyId")));// 选择的催收公司
			backUser.setGroupLevel(String.valueOf(params.get("groupId")));// 催收组
			backUser.setNotMineId(String.valueOf(params.get("currUserId")));// 剔除自己
			backUser.setUserStatus(BackUser.STATUS_USE);// 启用的催收员

			List<BackUser> backUserList = backUserService
					.findUserByDispatch(backUser);
			if (CollectionUtils.isNotEmpty(backUserList)) {
				SpringUtils.renderJson(response,
						JSONArray.fromObject(backUserList).toString(),
						new String[0]);
			}
		} catch (Exception e) {
			logger.error("findPerson error", e);
		}
	}

	// 转派
	@RequestMapping(value = "doDispatch")
	public String doDispatch(MmanLoanCollectionOrder order,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		JsonResult json = new JsonResult("-1", "转派失败");
		HashMap<String, Object> params = this.getParametersO(request);
		try {
			if (StringUtils.isNoneBlank(order.getId())) {
				Calendar calendar = Calendar.getInstance();
				int now = calendar.get(Calendar.HOUR_OF_DAY); 
				if(now >= 6){
					if (params.get("groupStatus") != null
							&& !"0".equals(params.get("groupStatus"))) {
						json.setMsg("只能相同组之间转派。请选择同组的数据");
					} else {
						BackUser backUser = (BackUser) request.getSession()
								.getAttribute(Constant.BACK_USER);
						json = mmanLoanCollectionRecordService.batchDispatch(
								backUser, order);
					}
				}else{
					json.setMsg("0点到6点之间不允许进行转派操作");
				}
			} else {
				json.setMsg("请选择要转派的订单");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		SpringUtils.renderDwzResult(response, "0".equals(json.getCode()),
				json.getMsg(), DwzResult.CALLBACK_CLOSECURRENT,
				params.get("parentId").toString());
		model.addAttribute("params", params);

		/*
		 * SpringUtils.renderDwzResult(response, "0".equals(json.getCode()),
		 * json.getMsg(), DwzResult.CALLBACK_CLOSECURRENT,
		 * params.get("parentId").toString());
		 */
		return null;
	}

	/**
	 * 转派订单
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("zhuanpai")
	@ResponseBody
	public Map<String, Object> zhuanpai(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Map<String, Object> map = new HashMap<String, Object>();

		return map;
	}

	/**
	 * 将cookie封装到Map里面
	 * 
	 * @param request
	 * @return
	 */
	private static Map<String, String> ReadCookieMap(HttpServletRequest request) {
		Map<String, String> cookieMap = new HashMap<String, String>();
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				cookieMap.put(cookie.getName(), cookie.getValue());
			}
		}
		return cookieMap;
	}

	/**
	 * 跳转到发送短信页面
	 * 
	 * @param model
	 *            需要发短信的手机号
	 * @return
	 */
	@RequestMapping("gotoSendMsg")
	public String gotoSendMsg(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		HashMap<String, Object> params = this.getParametersO(request);
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			if (StringUtils.isNotBlank(params.get("id") + "")) {
				MmanLoanCollectionOrder mmanLoanCollectionOrderOri = mmanLoanCollectionOrderService
						.getOrderById(params.get("id").toString());
				MmanUserInfo userInfo = mmanUserInfoService
						.getUserInfoById(mmanLoanCollectionOrderOri.getUserId());
				model.addAttribute("loanOrderId",
						mmanLoanCollectionOrderOri.getLoanId());
				model.addAttribute("userPhone", userInfo.getUserPhone());
				model.addAttribute("orderId",
						mmanLoanCollectionOrderOri.getUserId());
				model.addAttribute("userId", userInfo.getId());
				model.addAttribute("originalNum", userInfo.getUserPhone());
				model.addAttribute("msgCount", iSmsUserDao
						.getSendTotalMsgCount(mmanLoanCollectionOrderOri
								.getLoanId()));
				String  msgType =mmanLoanCollectionOrderOri.getCurrentOverdueLevel();
				if ("5".equals(msgType)) {
					List<String> list = new ArrayList<String>();
					list.add("3");
					list.add("4");
					list.add("5");
					map.put("msgType",list);
				}else  if("6".equals(msgType) || "7".equals(msgType)){
					List<String> list = new ArrayList<String>();
					list.add("5");
					map.put("msgType",list);
				}else if("3".equals(msgType)){
					List<String> list = new ArrayList<String>();
					list.add("3");
					map.put("msgType",list);
				}else{
					List<String> list = new ArrayList<String>();
					list.add("4");
					map.put("msgType",list);
				}
				model.addAttribute("msgs", templateSmsDao.getType(map));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}	
		model.addAttribute("params", params);
		return "mycollectionorder/smsSendDetail";
	}

	/**
	 * 发送催收短信
	 * 
	 * @param //mobiles
	 *            需要发送短信的手机号
	 * @param //smsContent
	 *            短信内容
	 * @param //isSendSmsToAll
	 *            是否发送给所有人
	 * @return
	 */
	@RequestMapping("sendMsg")
	public ServiceResult SendSms(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		JsonResult result = new JsonResult("-1", "发送短信失败");
		HashMap<String, Object> params = this.getParametersO(request);
		try {
			String mobiles = request.getParameter("phoneNumber");
			String msgId = request.getParameter("msgId");
			// String smsContent =
			// templateSmsDao.getTemplateSmsById(msgId).getContenttext();
			String smsContent = null;
			if (msgId == null || msgId == "") {
				result.setMsg("请选择需要发送的短信内容!");
			} else {
				smsContent = templateSmsDao.getTemplateSmsById(msgId)
						.getContenttext();
				String orderId = request.getParameter("loanOrderId");
				String userName = mmanUserInfoService.getUserInfoById(
						request.getParameter("orderId")).getRealname();
				String originalNum = request.getParameter("originalNum");
				String userId = request.getParameter("userId");
				smsContent = userName + smsContent;
				// 查询出该借款人所有的联系人
				List<MmanUserRela> userReal = mmanUserRelaService
						.getContactPhones(userId);
				List<String> phones = new ArrayList<String>();
				for (MmanUserRela mmanUserRela : userReal) {
					phones.add(mmanUserRela.getInfoValue());
				}
				if (phones.contains(mobiles) || mobiles.equals(originalNum)) {
					// 查询出对应借款订单信息
					MmanLoanCollectionOrder order = mmanLoanCollectionOrderService
							.getOrderWithId(orderId);
					// 查询出该订单当天已发短信的次数
					int count = smsUserService.getSendMsgCount(orderId);
					int overdueDays = order.getOverdueDays();
					// System.out.println("***********************************");
					// System.out.println("手机号:" + mobiles);
					// System.out.println("短息内容:" + smsContent);
					// System.out.println("借款编号:" + orderId);
					// System.out.println("订单逾期天数:" + overdueDays);
					// System.out.println("今日已发短信次数:" + count);
					// System.out.println("***********************************");
					// 逾期10天以内(包括10) 可发短信的数量为每天3条
					if (overdueDays <= 10) {
						if (count < 3) {
							sendMsg(result, mobiles, orderId, userName,
									smsContent, request);
						} else {
							result.setCode("3");
							result.setMsg("今日该订单短信已达上限");
						}
					} else {
						// 逾期10天以上(不包括10) 可发短信的数量为每天5条
						if (count < 5) {
							sendMsg(result, mobiles, orderId, userName,
									smsContent, request);
						} else {
							result.setCode("3");
							result.setMsg("今日该订单短信已达上限");
						}
					}
				} else {
					result.setCode("5");
					result.setMsg("请检查您输入的手机号码!");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("params", params);
		SpringUtils.renderDwzResult(response, "0".equals(result.getCode()),
				result.getMsg(), DwzResult.CALLBACK_CLOSECURRENT,
				params.get("parentId").toString());
		return null;
	}

	/**
	 * 发送短信方法
	 * 
	 * @param result
	 * @param mobiles
	 * @param orderId
	 * @param userName
	 * @param smsContent
	 * @throws InterruptedException
	 */
	private void sendMsg(JsonResult result, String mobiles, String orderId,
			String userName, String smsContent, HttpServletRequest request)
			throws InterruptedException {
		if (StringUtils.isNotBlank(smsContent)
				&& StringUtils.isNotBlank(mobiles)) {
			if (!SMS253Util.sendSmsDiyCL(mobiles, smsContent)) {
				result.setCode("204");
				result.setMsg("发送失败");
			} else {
				result.setMsg("发送成功");
				result.setCode("0");
				// 新增一条短信发送记录
				SmsUser msg = new SmsUser();
				BackUser user = this.loginAdminUser(request);
				msg.setSendUserId(user.getUuid());
				msg.setAddTime(new Date());
				msg.setLoanOrderId(orderId);
				msg.setSmsContent(smsContent);
				msg.setUserPhone(mobiles);
				msg.setUserName(userName);
				this.smsUserService.insert(msg);
				// 每个数据包发送后等待一秒 云峰短信有频率限制
				Thread.sleep(1000);
			}
		} else {
			result.setMsg("参数不正确");
		}
	}

	/**
	 * 分期还款计算
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("installmentPay")
	public String getInstallmentPay(HttpServletRequest request,HttpServletResponse response, Model model) {
		Map<String, String> params = this.getParameters(request);
		model.addAttribute("params", params);

		if(!params.containsKey("installmentpay") || StringUtils.isBlank(params.get("installmentpay"))){
			params.put("installmentpay","2");
		}
		try {
			if (StringUtils.isNotBlank(params.get("id"))) {
				MmanLoanCollectionOrder mmanLoanCollectionOrderOri = mmanLoanCollectionOrderService.getOrderById(params.get("id").toString());
				MmanUserLoan userLoan = mmanUserLoanService.get(mmanLoanCollectionOrderOri.getLoanId());
				if (userLoan != null) {
					model.addAttribute("ownMoney", userLoan.getLoanMoney());// 总本金
					model.addAttribute("overdueMoney", userLoan.getLoanPenalty());// 总滞纳金
					int count = Integer.valueOf(params.get("installmentpay"));
					// 获取分期明细信息
					List<InstallmentPayInfoVo> list = getInstallmentPayInfoList(count, userLoan);

					model.addAttribute("installmentPayInfoVoList", list);
					model.addAttribute("installmentList", BackConstant.typeMap);
				}

				List<InstallmentPayRecord> installmentPayRecordList = mmanLoanCollectionRecordService.findInstallmentList(params.get("id").toString());
				model.addAttribute("installmentPayRecordList", installmentPayRecordList);
			}
		}catch(Exception e){
			logger.error("分期还款计算异常(installmentPay)：",e);
		}
		return "mycollectionorder/toInstallmentPay";
	}

	private List<InstallmentPayInfoVo> getInstallmentPayInfoList(int count, MmanUserLoan userLoan) {
		if(count > 4){
			count = 2; // 分期最多为4期
		}
		List<InstallmentPayInfoVo> list = new ArrayList<InstallmentPayInfoVo>();
		InstallmentPayInfoVo installmentPayInfoVo = null;

		for (int i = 0 ; i < count; i++){
			installmentPayInfoVo = new InstallmentPayInfoVo();
			installmentPayInfoVo.setInstallmentType(BackConstant.typeNameMap.get(String.valueOf(i+1)));
			installmentPayInfoVo.setRepayTime(getNextWeek(i));
			BigDecimal stagesOwnMoney = userLoan.getLoanMoney().divide(new BigDecimal(count), 2, BigDecimal.ROUND_UP);
			installmentPayInfoVo.setStagesOwnMoney(stagesOwnMoney); // 分期本金
			BigDecimal stagesOverdueMoney = userLoan.getLoanPenalty().divide(new BigDecimal(count), 2, BigDecimal.ROUND_UP);
			installmentPayInfoVo.setStagesOverdueMoney(stagesOverdueMoney); // 分期滞纳金
			installmentPayInfoVo.setTotalRepay(stagesOwnMoney.add(stagesOverdueMoney)); // 分期还款总计
			if (i == 0) {
				BigDecimal serviceCharge = new BigDecimal(10).multiply(new BigDecimal(count));
				installmentPayInfoVo.setServiceCharge(serviceCharge);
				installmentPayInfoVo.setTotalRepay(stagesOwnMoney.add(stagesOverdueMoney).add(serviceCharge)); // 分期还款总计
			}
			list.add(installmentPayInfoVo);
		}
		return list;
	}

	private Date getNextWeek(int i) {
		Calendar calendar = Calendar.getInstance();
		Date date = new Date(System.currentTimeMillis());
		calendar.setTime(date);
		calendar.add(Calendar.WEEK_OF_YEAR, i);
		return calendar.getTime();
	}

	/**
	 * 分期账单创建
	 * @param request
	 * @param response
	 * @param model
     * @return
     */
	@RequestMapping("insertInstallmentPayRecord")
	public void insertInstallmentPayRecord(HttpServletRequest request,HttpServletResponse response, Model model) {
		String url = null;
		String erroMsg = null;
		List<InstallmentPayRecord> installmentPayRecordList = null;
		Map<String,Object> map = new HashMap<String,Object>();
		JsonResult result = new JsonResult("-1", "创建分期失败");
		Map<String, String> params = this.getParameters(request);
		BackUser backUser = (BackUser) request.getSession().getAttribute(Constant.BACK_USER);
		try {
			List<InstallmentPayRecord> countList = mmanLoanCollectionRecordService.findInstallmentList(params.get("id").toString());
//			countList = null;
			if(CollectionUtils.isEmpty(countList)){
				MmanLoanCollectionOrder mmanLoanCollectionOrderOri = mmanLoanCollectionOrderService.getOrderById(params.get("id").toString());
				MmanUserLoan userLoan = mmanUserLoanService.get(mmanLoanCollectionOrderOri.getLoanId());
				if(userLoan != null){
					map.put("loanUserName", mmanLoanCollectionOrderOri.getLoanUserName());
					map.put("loanUserPhone", mmanLoanCollectionOrderOri.getLoanUserPhone());
					int count = Integer.valueOf(params.get("installmentpay"));
					// 获取分期明细信息
					List<InstallmentPayInfoVo> list = getInstallmentPayInfoList(count, userLoan);
					params.put("roleId",backUser.getRoleId());
					params.put("operationUserId", backUser.getId().toString());
					JsonResult withholdingResult = mmanLoanCollectionRecordService.xjxWithholding(params);
					withholdingResult.setCode("0");
					// 代扣成功
					if("0".equals(withholdingResult.getCode())){
						result = mmanLoanCollectionRecordService.insertInstallmentPayRecord(list,mmanLoanCollectionOrderOri);
						installmentPayRecordList = (List<InstallmentPayRecord>)result.getData();
						map.put("installmentPayRecordList",installmentPayRecordList);
					}
				}
			}else{
				result.setMsg("该订单已创建过了");
			}
			String json = JSONUtil.beanToJson(map);
			response.getWriter().write(json);
			response.getWriter().flush();

		} catch (Exception e) {
			logger.error("分期账单创建失败！", e);
		}
	}

	@RequestMapping("getContactInfo")
	private String gotoGetContactInfoPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		HashMap<String, Object> params = this.getParametersO(request);
		String phoneNum = request.getParameter("phoneNum");
		if (phoneNum != "" && phoneNum != null) {
			model.addAttribute("contactInfo",
					mmanUserInfoService.getContactInfo(phoneNum));
		}
		model.addAttribute("params", params);
		return "mycollectionorder/getContactInfo";
	}
	
	/**
	 * 减免页面
	 * @param request
	 * @param response
	 * @param orderId
	 * @param model
	 * @return
	 */
	@RequestMapping("jianmian")
	public String jianmian(HttpServletRequest request,
			HttpServletResponse response, String orderId, Model model) {
		HashMap<String, Object> params = this.getParametersO(request);
		if (StringUtils.isNotBlank(params.get("id") + "")) {
			MmanLoanCollectionOrder mmanLoanCollectionOrderOri = mmanLoanCollectionOrderService
					.getOrderById(params.get("id").toString());
			MmanUserLoan userLoan = mmanUserLoanService
					.get(mmanLoanCollectionOrderOri.getLoanId());
			model.addAttribute("userLoan", userLoan);
			model.addAttribute("collectionOrder", mmanLoanCollectionOrderOri);
			MmanUserInfo userInfo = mmanUserInfoService
					.getUserInfoById(mmanLoanCollectionOrderOri.getUserId());
			model.addAttribute("userInfo", userInfo);
			List<CreditLoanPayDetail> detailList = creditLoanPayDetailService
					.findPayDetail(mmanLoanCollectionOrderOri.getPayId());
			BigDecimal payMonery = new BigDecimal(0);
			if (detailList != null) {
				for (CreditLoanPayDetail pay : detailList) {
					payMonery = payMonery.add(pay.getRealMoney()).add(
							pay.getRealPenlty());
				}
			}
			
			SysUserBankCard userCar = sysUserBankCardService
					.findUserId(mmanLoanCollectionOrderOri.getUserId());
			model.addAttribute("userCar", userCar);// 已还金额
			model.addAttribute("payMonery", payMonery);// 本金
			model.addAttribute("detailList", detailList);
			//减免类型
			List<SysDict> statulist = sysDictService
					.getStatus("xjx_collection_derate");
			model.addAttribute("statulist", statulist);
		}
		model.addAttribute("params", params);
		return "mycollectionorder/jmlist";
	}
	/**
	 *  减免确认
	 * @return
	 */
	@RequestMapping("addloanCollPaymoney")
	public String addloanCollPaymoney(HttpServletRequest request,
			HttpServletResponse response,  Model model){
		JsonResult result = new JsonResult("-1", "申请减免失败！！");
		String url = null;
		String erroMsg = null;
		HashMap<String, Object> params = this.getParametersO(request);
		BackUser backUser = (BackUser) request.getSession().getAttribute(//获取用户信息
				Constant.BACK_USER);
		 try {
				 MmanLoanCollectionOrder mmanLoanCollectionOrderOri = mmanLoanCollectionOrderService	.getOrderById(params.get("id").toString());
			 MmanUserLoan userLoan = mmanUserLoanService.get(mmanLoanCollectionOrderOri.getLoanId());
             BigDecimal remoney = new BigDecimal(params.get("deductionmoney").toString());
			 CreditLoanPay loanPay =CreditLoanPayService.get(mmanLoanCollectionOrderOri.getPayId());
			// BigDecimal ReceivableMoney =loanPay.getReceivableMoney();
			 BigDecimal RealgetInterest =loanPay.getReceivableInterest();
			 if(loanPay.getRealMoney().compareTo(userLoan.getLoanMoney())>=0){
				 if(remoney.compareTo(userLoan.getLoanPenalty())<=0){
					 if((RealgetInterest.compareTo(remoney)>=0)){
						 if(!"6".equalsIgnoreCase(mmanLoanCollectionOrderOri.getStatus())){
							 if (!"4".equals(mmanLoanCollectionOrderOri.getStatus())) {
								 if(!"7".equals(mmanLoanCollectionOrderOri.getStatus())){
									 //减免类型
									 List<SysDict> statulist = sysDictService
											 .getStatus("xjx_collection_derate");
									 //减免审核状态
									 List<SysDict> jmstatulist = sysDictService
											 .getStatus("xjx_collection_order_state");
									 model.addAttribute("statulist", statulist);
									 params.put("orderId", mmanLoanCollectionOrderOri.getId());
									 params.put("userId", mmanLoanCollectionOrderOri.getUserId());
									 params.put("deductionmoney", params.get("deductionmoney"));
									 params.put("deductionremark", params.get("deductionremark"));
									 params.put("loanPenlty", userLoan.getLoanPenalty());
									 params.put("loanId", mmanLoanCollectionOrderOri.getLoanId());
									 params.put("operationUserId",  String.valueOf(backUser.getId()));
									 params.put("type", statulist.get(0).getValue());
									 params.put("note", jmstatulist.get(2).getValue());
									 params.put("payId", mmanLoanCollectionOrderOri.getPayId());
									 params.put("name", mmanLoanCollectionOrderOri.getLoanUserName());
									 params.put("phone", mmanLoanCollectionOrderOri.getLoanUserPhone());
									 params.put("orderStatus",mmanLoanCollectionOrderOri.getStatus());
									 result=auditCenterService.saveorderdeduction(params);
								 }else{
									 result.setMsg("减免审核成功订单，不能再次申请减免");
								 }
							 }else {
								 result.setMsg("催收成功订单，不能申请减免");
							 }
						 }else{
							 result.setMsg("申请减免中的订单， 不能重复申请减免");
						 }
					 }else {
						 result.setMsg("减免失败 减免金额不能大于剩余应还金额");
					 }
				 }else {
					 result.setMsg("减免金额 不能大于滞纳金");
				 }
			 }else{
				 result.setMsg("未还足本金 不能予以减免");
			 }
		 } catch (Exception e) {
			result.setMsg("申请减免异常");
			logger.error("申请减免异常 addloanCollPaymoney  ",e);
	}	
		 SpringUtils.renderDwzResult(response, "0".equals(result.getCode()),
					result.getMsg(), DwzResult.CALLBACK_CLOSECURRENT,
					params.get("parentId").toString());
			model.addAttribute(MESSAGE, erroMsg);
			model.addAttribute("params", params);
		
		return url;
	}

	
	@RequestMapping("getorderPage")
	public String getorderPage(HttpServletRequest request,HttpServletResponse response, Model model) {
		try {
			HashMap<String, Object> params = getParametersO(request);
			//add  减免列表默认申请中状态
			if(!params.containsKey("status") && params.containsKey("--")){
				params.put("status","0");
				params.put("pageNum",1);
			}
			params.put("noAdmin", Constant.ADMINISTRATOR_ID);
			PageConfig<Mman_loan_collection_orderdeduction> pageConfig = collection_orderdeductionService.findPage(params);
			model.addAttribute("pm", pageConfig);
			model.addAttribute("params", params);// 用于搜索框保留值
		} catch (Exception e) {
			logger.error("getCompanyPage error", e);
		}
		return "mycollectionorder/getorderPage";
	}

	@RequestMapping("testKh")
	public String testKh(HttpServletRequest request,HttpServletResponse response, Model model) {
		try {
			Date date = new Date();
			HashMap<String,Object> params = new HashMap<String,Object>();
//			params.put("currDate", DateUtil.getBeforeOrAfter(date,-1));
			params.put("currDate", request.getParameter("currDate"));
			params.put("begDate", request.getParameter("begDate"));
			params.put("endDate", request.getParameter("endDate"));
			params.put("isFirstDay", date.getDate());   //获取当前日
			// 考核统计
			countCollectionAssessmentService.countCallAssessment(params);
		} catch (Exception e) {
			logger.error("testKh error", e);
		}
		return null;
	}

	@RequestMapping("testGl")
	public String testGl(HttpServletRequest request,HttpServletResponse response, Model model) {
		try {
			Date date = new Date();
			HashMap<String,Object> params = new HashMap<String,Object>();
//			params.put("currDate", DateUtil.getBeforeOrAfter(date,-1));
			params.put("currDate", request.getParameter("currDate"));
			params.put("begDate", DateUtil.getDayFirst());
			params.put("endDate", DateUtil.getDayLast());
			params.put("isFirstDay", date.getDate());   //获取当前日
			// 管理统计
			countCollectionManageService.countCallManage(params);
		} catch (Exception e) {
			logger.error("testGl error", e);
		}
		return null;
	}

}
